<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item :label="t('instance.fields.awardsName')" prop="awardsName">
        <el-input
          v-model="queryParams.awardsName"
          :placeholder="t('common.inputTextPlaceholder') + t('instance.fields.awardsName')"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          {{ t('common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          {{ t('common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['awards:instance:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          {{ t('action.add') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <vxe-toolbar ref="toolbarRef" custom />
    <vxe-table
      id="iInstance-table"
      ref="tableRef"
      v-loading="loading"
      :data="list"
      stripe
      :custom-config="vxeTableConfig"
      :column-config="{ resizable: true }"
      :size="vxeTableSize"
    >
      <vxe-column :title="t('common.index')" type="seq" field="seq" width="60" align="center" />
      <vxe-column
        :title="t('instance.fields.awardsName')"
        field="awardsName"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('instance.fields.year')"
        field="year"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      />
      <vxe-column
        :title="t('instance.fields.awardsType')"
        field="awardsType"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ findInTemplate(scope.row.templateId) }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('instance.fields.status')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ getStatus(scope.row) }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('instance.fields.judgeStatus')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ getJudgeStatus(scope.row.judgeStatus) }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('instance.fields.studentNum')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <p
            >{{ t('instance.fields.total') }}:
            {{ (scope.row.masterCount ?? 0) + (scope.row.doctorCount ?? 0) }}</p
          >
          <p>{{ t('instance.fields.masterTotal') }}: {{ scope.row.masterCount }}</p>
          <p>{{ t('instance.fields.doctorTotal') }}: {{ scope.row.doctorCount }}</p>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('instance.fields.onlineApply')"
        field="onlineApply"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          <div>{{ scope.row.onlineApply ? t('common.yes') : t('common.no') }}</div>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('instance.fields.applyTime')"
        align="center"
        show-header-overflow
        show-overflow
        min-width="130"
      >
        <template #default="scope">
          <div>{{ formatDate(scope.row.applyStartTime) }}</div>
          <div>{{ formatDate(scope.row.applyEndTime) }}</div>
        </template>
      </vxe-column>
      <vxe-column
        :title="t('instance.fields.qualificationReview')"
        field="qualificationReview"
        align="center"
        show-header-overflow
        show-overflow
        min-width="100"
      >
        <template #default="scope">
          {{ scope.row.qualificationReview ? t('common.yes') : t('common.no') }}
        </template>
      </vxe-column>
      <vxe-column
        :title="t('common.operate')"
        field="operator"
        align="center"
        fixed="right"
        width="150"
      >
        <template #default="scope">
          <div class="flex flex-col items-center">
            <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['awards:instance:update']"
            >
              {{ t('action.edit') }}
            </el-button>
            <el-button link type="primary" @click="handleViewCandidate(scope.row)">
              {{ t('instance.index.viewCandidate') }}
            </el-button>
            <el-button link type="primary" @click="handleViewScene(scope.row)">
              {{ t('instance.index.judgeScene') }}
            </el-button>
            <el-button
              v-if="scope.row.differenceSelection"
              link
              type="primary"
              @click="handleDifferenceSelection(scope.row)"
            >
              {{ t('instance.index.differenceSelection') }}
            </el-button>
            <!-- 评选状态 1=未开始 2=初评进行中 3=初评结束 4=终评进行中 5=终评结束 -->
            <template v-if="scope.row.preliminaryEvaluation">
              <!-- 双阶段评奖 -->
              <el-button
                v-if="scope.row.judgeStatus === 1"
                link
                type="primary"
                @click="handleStartInitial(scope.row)"
                :loading="startLoading"
              >
                {{ t('instance.index.startInitial') }}
              </el-button>
              <el-button v-if="scope.row.judgeStatus === 2" link type="primary" disabled>
                {{ t('instance.index.onInitial') }}
              </el-button>
              <el-button
                v-if="scope.row.judgeStatus === 3"
                link
                type="primary"
                @click="handleStartFinal(scope.row)"
                :loading="startLoading"
              >
                {{ t('instance.index.startFinal') }}
              </el-button>
              <el-button v-if="scope.row.judgeStatus === 4" link type="primary" disabled>
                {{ t('instance.index.onFinal') }}
              </el-button>
              <el-button v-if="scope.row.judgeStatus === 5" link type="primary" disabled>
                {{ t('instance.index.over') }}
              </el-button>
            </template>
            <template v-else>
              <!-- 单阶段评奖 -->
              <el-button
                v-if="scope.row.judgeStatus === 1"
                link
                type="primary"
                @click="handleStartFinal(scope.row)"
                :loading="startLoading"
              >
                {{ t('instance.index.startFinal') }}
              </el-button>
              <el-button v-if="scope.row.judgeStatus === 4" link type="primary" disabled>
                {{ t('instance.index.onFinal') }}
              </el-button>
              <el-button v-if="scope.row.judgeStatus === 5" link type="primary" disabled>
                {{ t('instance.index.over') }}
              </el-button>
            </template>
          </div>
        </template>
      </vxe-column>
    </vxe-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <InstanceForm ref="formRef" @success="getList" />
  <!-- 差额评选 -->
  <DifferenceSelection ref="differenceSelectionRef" />
</template>

<script setup lang="ts">
import { useAppStore } from '@/store/modules/app'
import { formatDate } from '@/utils/formatTime'
import { InstanceApi, InstanceVO } from '@/api/awards/instance'
import { TemplateApi, TemplateVO } from '@/api/awards/template'
import type { VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from 'vxe-table'
import InstanceForm from './InstanceForm.vue'
import DifferenceSelection from './components/differenceSelection/DifferenceSelection.vue'

/** 评奖 列表 */
defineOptions({ name: 'Instance' })

const router = useRouter() // 路由对象
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const toolbarRef = ref<VxeToolbarInstance>()
const tableRef = ref<VxeTableInstance>()
const differenceSelectionRef = ref<InstanceType<typeof DifferenceSelection>>() // 差额评选的弹窗

const loading = ref(true) // 列表的加载中
const list = ref<InstanceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  templateId: undefined,
  awardsName: undefined,
  year: undefined,
  noticeUrl: undefined,
  onlineApply: undefined,
  applyStartTime: [],
  applyEndTime: [],
  conditionJson: undefined,
  qualificationReview: undefined,
  differenceSelection: undefined,
  preliminaryEvaluation: undefined,
  awardsType: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const vxeTableConfig: VxeTablePropTypes.CustomConfig = {
  storage: true,
  mode: 'drawer',
  checkMethod({ column }) {
    return !['seq', 'operator'].includes(column.field)
  }
}

const appStore = useAppStore()
const vxeTableSize = computed(() => appStore.getCurrentSizeVxe)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await InstanceApi.getInstancePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof InstanceForm>>()
const openForm = (type: string, id?: string) => {
  formRef.value?.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await InstanceApi.deleteInstance(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// 通过时间计算申请状态
const getStatus = (row: InstanceVO) => {
  if (!row.onlineApply) {
    return t('instance.index.status.unset')
  }
  const now = new Date().getTime()
  if (now < row.applyStartTime) {
    return t('instance.index.status.notStarted')
  } else if (now > row.applyEndTime) {
    return t('instance.index.status.ended')
  } else {
    return t('instance.index.status.underway')
  }
}

// 计算评选状态 1=未开始 2=初评进行中 3=初评结束 4=终评进行中 5=终评结束
const getJudgeStatus = (status: number) => {
  switch (status) {
    case 1:
      return t('instance.index.judgeStatus.notStarted')
    case 2:
      return t('instance.index.judgeStatus.preliminaryEvaluation')
    case 3:
      return t('instance.index.judgeStatus.preliminaryEvaluationEnd')
    case 4:
      return t('instance.index.judgeStatus.finalEvaluation')
    case 5:
      return t('instance.index.judgeStatus.finalEvaluationEnd')
    default:
      return ''
  }
}

const handleViewCandidate = (row: InstanceVO) => {
  router.push('/awards/instance-candidate/' + row.id)
}

const handleViewScene = (row: InstanceVO) => {
  router.push('/awards/judge-scene/' + row.id)
}

const handleDifferenceSelection = (row: InstanceVO) => {
  console.log('差额评选', row)
  differenceSelectionRef.value?.open(row.id)
}

const startLoading = ref(false)
// 开启初评
const handleStartInitial = async (row: InstanceVO) => {
  if (row.judgeStatus !== 1) {
    return
  }
  try {
    await message.confirm(t('instance.index.startInitialConfirm'))
  } catch {
    return
  }
  startLoading.value = true
  try {
    await InstanceApi.startInitial(row.id)
    message.success(t('common.operSuccess'))
    getList()
  } finally {
    startLoading.value = false
  }
}

// 开启终评
const handleStartFinal = async (row: InstanceVO) => {
  if (row.judgeStatus !== 1 && row.judgeStatus !== 3) {
    return
  }
  try {
    await message.confirm(t('instance.index.startFinalConfirm'))
  } catch {
    return
  }
  startLoading.value = true
  try {
    await InstanceApi.startFinal(row.id)
    message.success(t('common.operSuccess'))
    getList()
  } finally {
    startLoading.value = false
  }
}

// 模版下拉集合
const templates = ref<TemplateVO[]>([])
// 找到评奖对应的奖项(实例找模版)
const findInTemplate = (id: string) => {
  return templates.value.find((item) => item.id === id)?.awardsName
}

/** 初始化 **/
onMounted(() => {
  getList()
  TemplateApi.getTemplateSimpleList().then((response) => {
    templates.value = response
  })

  const table = tableRef.value
  const toolbar = toolbarRef.value
  if (table && toolbar) {
    table.connect(toolbar)
  }
})
</script>

<style lang="scss" scoped>
:deep(.vxe-cell .el-button + .el-button) {
  margin-left: 0;
}
</style>
